package com.feinno.urcs.group.dao;

import com.feinno.database.DataRow;
import com.feinno.database.DataTable;
import com.feinno.database.Database;
import com.feinno.urcs.group.api.FXUserIndexService;
import com.feinno.urcs.group.api.GroupIndexService;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.interop.entity.FXCatalogIndex;
import com.feinno.urcs.group.util.DateUtils;
import com.feinno.urcs.group.util.URIUtils;
import com.feinno.urcs.types.MobileNo;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceImplementation;
import org.helium.framework.annotations.ServiceSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Date;

/**
 * Created by honghao on 5/4/15.
 */
@ServiceImplementation
public class GroupIndexServiceImplFetion implements GroupIndexService {
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupIndexServiceImplFetion.class);
	@FieldSetter("${GGRPDB}")
	private Database ggrpDb;
	@FieldSetter("${MaxMemberCount}")
	private int maxMemberCount;
	@ServiceSetter
	private FXUserIndexService fetionIndexService;

	@Override
	public GroupIndex getGroupById(int groupId) throws SQLException {
		String sql = "SELECT LogicPool FROM GGRP_SearchGroup where GroupId=?";
		GroupIndex index = null;
		DataTable dt = ggrpDb.executeTable(sql, groupId);
		if (dt.getRows().size() == 1) {
			int logicalPoolId = dt.getRow(0).getInt(1);
			index = new GroupIndex(groupId, logicalPoolId);

		}
		return index;
	}

	@Override
	public GroupIndex getGroupByUri(String groupUri) throws SQLException {
		return getGroupById(URIUtils.getGroupIdFromUri(groupUri));
	}

	@Override
	public GroupIndex getGroupByConversationId(String conversationId) throws SQLException {
		String sql = "SELECT * FROM GGRP_SearchGroup where ConversationId=?";
		DataTable dt = ggrpDb.executeTable(sql, conversationId);
		if (dt.getRows().size() == 1) {
			DataRow row = dt.getRow(0);
			int groupId = row.getInt("GroupId");
			int pool = row.getInt("LogicPool");
			return new GroupIndex(groupId, pool);
		} else {
			return null;
		}
	}

	@Override
	public GroupIndex createGroup(String conversationId, String subject, MobileNo adminMobileNo) throws Exception {
		GroupIndex index = null;

		//TODO 需要获取这两个值
		FXCatalogIndex fxCatalogIndex = fetionIndexService.getFXCatalogIndex(adminMobileNo);
		int fxUserId = fxCatalogIndex.getUserId();
		int logicPool = fxCatalogIndex.getLogicalPoolId();
//		int fxUserId = fetionIndexService.getFxUserId(adminMobileNo);
// 		int logicPool = userLogicPoolService.getLogicPool(fxUserId);
		String superAdmin = String.format("sipc:%s@gmcc.feition.bj.10086.cn;p=%s", fxUserId, logicPool);
		DataTable table = ggrpDb.spExecuteTable("USP_GetNextGUID", null);
		int groupId = table.getRow(0).getInt(1);

		String insertsql = "insert into GGRP_SearchGroup(GroupId,LogicPool,ConversationId,Name,SuperAdmin,CreateTime,EnableSearched,GroupLabel,GroupType,Introduce,MaxMemberCount,MemberCount,PortraitCrc,ReservedFlag,ValidType,WebActivity,CategoryId) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";


		Date nowUtc = DateUtils.getUTCNow();
		Object[] args = {
				groupId,//GroupId
				logicPool,// LogicPool
				conversationId, // ConversationId,
				subject,// GroupName,
				superAdmin, //SuperAdmin
				new java.sql.Date(nowUtc.getTime()),//CreateTime,
				0,// EnableSearched,
				"",// GroupLabel,
				1,// GroupType,
				"",// Introduce,
				maxMemberCount,// MaxMemberCount,
				1,// MemberCount,
				0,// PortraitCrc,
				0,// ReservedFlag,
				0,// ValidType,
				0,// WebActivity
				0//CategoryId
		};

		ggrpDb.executeNonQuery(insertsql, args);
		index = new GroupIndex(groupId, logicPool);

		return index;
	}

	@Override
	public boolean deleteGroup(int groupId) throws SQLException {
		String sql = "delete from GGRP_SearchGroup where GroupId =?";
		int ret = ggrpDb.executeNonQuery(sql, groupId);
		if (ret != 1) {
			LOGGER.error("deleteGroup Unexcepted ret=" + ret);
			return false;
		} else {
			return true;
		}
	}
}
